//= require <openlayers_control_click>
Policies_Ui_Map = Class.create({
    map_ : "",
    wms_url_ : "",
    wms_layer_ : false,
    layer_cnt_ : 0,
    legend_url_ : "",
    is_disabled_ : false,
    timeout_id_ : 0,
    initialize: function(wms_url, projection, arr_bbox, max_resolution, clickable, legend_url, arr_zoom_bbox) 
    {
        var options = {
            projection: new OpenLayers.Projection("EPSG:"+projection),
            displayProjection: new OpenLayers.Projection("EPSG:"+projection),
            maxResolution: max_resolution,
            maxExtent: new OpenLayers.Bounds(arr_bbox[0], arr_bbox[1], arr_bbox[2], arr_bbox[3]),
            controls: [
                        new OpenLayers.Control.Navigation(),
                        new OpenLayers.Control.PanZoom(),
                        new OpenLayers.Control.OverviewMap()
                    ]
        };
        this.wms_url_ = wms_url;
        if ($('no_js_map')!=null)
            $('no_js_map').hide();
        this.resizeWindow();
        $('map').removeClassName('skip');
        this.map_ = new OpenLayers.Map('map', options);
        this.addLayer(arr_zoom_bbox);
        if(clickable)
        {
            var click = new OpenLayers.Control.Click(this.map_);
            this.map_.addControl(click);
            click.activate();
        }
        else
        {
            this.legend_url_ = legend_url;
            $('map').insert({'bottom': '<div id="legend"><img src="' + this.legend_url_ +'&d='+ ++this.layer_cnt_  +'&SERVICE=WMS&VERSION=1.1.1&layer=base_layer&REQUEST=getlegendgraphic&FORMAT=image/png" class="ol_legend" /></div>'});
            $('map_props').observe('submit', this.updateParams.bindAsEventListener(this));
            //little browser detection-hack, because  < IE 7 don't support position:fixed
            if(Prototype.Browser.IE && (parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6 || parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7))
                return false;
            new Policies_Analysis_Window();
        }
    },
    updateParams : function(event)
    {
        var params = '';
        $$('#map_props select').each(function(element){
            params +=  element.readAttribute('name') + '=' + element.value + '&';
        }.bind(params));
        $$('#map_props input').each(function(element){
            if(element.readAttribute('type') == 'radio' || element.readAttribute('type') == 'checkbox')
            { 
                if(element.checked)
                    params +=  element.readAttribute('name') + '=' + element.value.gsub("#", "") + '&';
            }
            else
                params +=  element.readAttribute('name') + '=' + element.value.gsub("#", "") + '&';
        }.bind(params));
        if(event != undefined)
            event.stop();
        if(!this.is_disabled_)
        {
            new Ajax.Request($('map_props').action, {
                method: "post",
                parameters : params,
                onSuccess: this.setFocusToMap.bind(this),
                onFailure: function(){$('map_props').submit();},
                onLoading: this.updateSubmitButton.bind(this)
            });
        }
    },
    updateSubmitButton : function()
    {
        $('refreshmap').writeAttribute('disabled', 'disabled');
        this.is_disabled_ = true;
    },
    setFocusToMap : function()
    {
        window.location.href = '#map';
        this.updateLegend();
    },
    updateLegend : function()
    {
        this.addLayer(false);
        var img_preloader = new Image();
        img_preloader.onload = function(){
            $('legend').update('<img src="'+img_preloader.src+'" class="ol_legend" />');
            $('legend').setStyle({'height': img_preloader.height + 'px', 'width': img_preloader.width + 'px'});    
        }.bind(this);
        img_preloader.src = this.legend_url_ +'&d='+ ++this.layer_cnt_ +'&SERVICE=WMS&VERSION=1.1.1&layer=data_layer&REQUEST=getlegendgraphic&FORMAT=image/png';
    },
    addLayer : function(arr_zoom_bbox)
    {
        if(this.wms_layer_ !== false)
        {
            var bounds = this.wms_layer_.getExtent();
            this.map_.removeLayer(this.wms_layer_);
            this.wms_layer_.destroy();
        }
        this.wms_layer_ = new OpenLayers.Layer.WMS( "OpenLayers WMS" + ++this.layer_cnt_, this.wms_url_+'&d='+this.layer_cnt_, {layers: 'BEZ'}, {singleTile: true});
        this.map_.addLayer(this.wms_layer_);
        if(arr_zoom_bbox !== false && arr_zoom_bbox != undefined)
        {
            this.map_.zoomToExtent(new OpenLayers.Bounds(arr_zoom_bbox[0], arr_zoom_bbox[1], arr_zoom_bbox[2], arr_zoom_bbox[3]));
        }
        else
        {
            if(!this.is_disabled_)
                this.map_.zoomToMaxExtent();
            else
                this.map_.zoomToExtent(bounds);
        }
        if(this.is_disabled_)
            $('refreshmap').writeAttribute('disabled', false);
        this.is_disabled_=false;
    }, 
    resizeWindow : function()
    {
        $('content').removeClassName('content');
        var height = document.viewport.getHeight()-$('content').cumulativeOffset().top;
        $('content').setStyle({'height': height + 'px'});
        $('optionsidebar').setStyle({'height': height + 'px', 'overflow': 'auto', 'margin-bottom' : 0});
        $('map').setStyle({'height': height + 'px'});
    }    
});
